import { TableDetailComponent } from './../tableDetail/tableDetail.component';
import { TableComponent } from './../table/table.component';
import { NavController, NavParams } from 'ionic-angular';
import { DeviceManager } from './../../common/mpj-deviceCenter/src/deviceManager';
import { PrintComponentService, PrintParams } from './../device/printer/templates/printcontainer.component';
import { NumberPanelService } from './../../component/primeng/numberpanel/numberpanel.service';
import { ConfirmParams } from './../../component/primeng/confirm/confirm.module';
import { NumberPanel } from './../../component/primeng/numberpanel/numberpanel.component';
import { MdSnackBar } from '@angular/material';
import { MdDialog } from "@angular/material";
import { ObjectCopier } from './../../common/objectCopier';
import { ModifierService } from './../../service/modifier.service';
import { CacheManager } from './../../common/cacheManager';
import { TableMessageHandle } from './../../common/messageHandle/tableMsgHandle';
import { MessageHandleManager } from './../../common/messageHandle/msgHandleMg';
import { Table, SoldOut, ComboItem } from './../../model/clerkDataContext';
import { TableService } from './../../service/table.service';
import { InnerMessageType, FNCManager } from './../../common/fncManager';
import { Component, Input, OnDestroy, ElementRef, ViewChild, Renderer } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NavigateService } from "../../service/index";
import { InventoryService, CartService } from "../../service/index";
import { Cart, Inventory, Modifier, Order } from "../../model/clerkDataContext";
import { MessageBoxService, MessageResult, GrowlMessageType } from '../../component/messageBoxService';
import { OrderMoreService } from "./view/orderMore";
import { OrderConfirmService } from './view/orderConfirm';
import { OrderDetail, OrderDetailService } from "./view/orderDetail";
import { loadingMask } from "./../../component/decorators";
import { CompletePayMessagehandle } from "../../common/messageHandle/completePayMsgHandle";
import { OrderPickUpService } from "./view/orderPickUp";
import * as lodash from "lodash";
import { StoreService } from "../../service/store.service";
import { guid } from "../../common/guid";
import { SoldOutMsgHandle } from "../../common/messageHandle/soldOutMsgHandle";

@Component({
    //moduleId: module.id,
    selector: 'order',
    templateUrl: "./order.component.html",
    styleUrls: ['./order.component.scss']
})
export class OrderComponent implements OnDestroy {
    isShowClassify: boolean = true;
    transformStyle = "";
    //orderModel: boolean = false;
    isShowThisOrder = false;
    searchModel = false;
    showKeyboard = true;
    //修改图标的样式(旋转180度)
    private tableMsgHandle: TableMessageHandle;
    commonMods: Modifier[] = [];
    soldOuts: SoldOut[] = [];
    printerManager;
    maxInvtQty: number = 10000;
    soldOutMsgHandle: SoldOutMsgHandle;
    @ViewChild('end') endSideNav: ElementRef;
    @ViewChild('searchInput') searchInput: ElementRef;
    @ViewChild('invtList') invtList: ElementRef;
    @ViewChild('searchInvtList') searchInvtList: ElementRef;
    @ViewChild('pickup') pickup: ElementRef;
    @ViewChild(OrderDetail)
    orderDetailComponent: OrderDetail;
    completePayMsghandle: CompletePayMessagehandle;
    // onToggleClassify() {
    //     this.isShowClassify = !this.isShowClassify;
    //     if (this.isShowClassify) {
    //         this.transformStyle = "rotate(0deg)";
    //     } else {
    //         this.transformStyle = "rotate(180deg)";
    //     }
    // }
    //切换点单模式（顾客模式：true或者店员模式:false）
    /*onSwitchOrderModel(){
        this.orderModel = !this.orderModel;
        this.msgs = [];
        if(this.orderModel) {  
            this.msgs.push({ severity: 'info', summary: '', detail: '已切换为顾客模式点单' });
        } else {
            this.msgs.push({ severity: 'info', summary: '', detail: '已切换为店员模式点单' });
        }
    }*/
    constructor(
        private router: NavigateService,
        private invtSvr: InventoryService,
        public cartSvr: CartService,
        private msgSvr: MessageBoxService,
        private acRouter: ActivatedRoute,
        private tableSvr: TableService,
        private orderDetailService: OrderDetailService,
        private rd: Renderer,
        private modSvr: ModifierService,
        private dialog: MdDialog,
        public snackBar: MdSnackBar,
        private storeSvr: StoreService,
        public navCtrl: NavController,
        private navParams: NavParams
    ) { }


    categoryList: any[];
    inventoryList = [];
    checkedCatetory = {};
    tableId: string;
    currentInvt = {};
    currentTable: Table;
    listPage: number = 1; //当前查询页数
    listPageCount: number = 10; //查询每页数据条数
    cachePage: number = 1; //从缓存中查询的页数
    cachePageCount: number = 10; //从缓存中每页查询的条数
    disabledScroll: boolean = false; //禁用无限滚动
    disabledCacheScroll: boolean = false; //禁用搜索商品的滚动加载数据
    queryCacheDataing: boolean = false; // 是否在查询缓存商品
    queryDataing: boolean = false //是否在查询数据中
    loadingInvt: boolean = true;
    private sub;
    private zoneId;
    key = ""; //搜索关键字
    searchInventories; //搜索出的商品列表
    currentOrder: Order;
    commonRemarks;  //通用商品选项

    async ionViewWillEnter() {
        this.router.registGoBack(this.navGoBack.bind(this));
        this.printerManager = DeviceManager.Current.getManagerByType("printerManager");
        this.categoryList = await this.invtSvr.GetCategoryList();
        this.soldOuts = await this.invtSvr.getSoldOutInvt();
        this.soldOuts = this.handleSoldout(this.soldOuts);
        this.categoryList.push({ id: "", name: "所有" });
        //清空购物车
        this.cartSvr.Clear();
        if (this.categoryList && this.categoryList.length) {
            this.categoryList.sort((a, b) => {
                return a.showOrder - b.showOrder;
            });
            await this.onCategoryClick(this.categoryList[0]);
        }
        // this.sub = this.acRouter.params.subscribe(params => {
        this.tableId = this.navParams.get('tableId');
        // this.zoneId = params['zoneId'];
        // });
        this.currentTable = await this.tableSvr.GetTableInfo(this.tableId);
        this.commonMods = await this.modSvr.getCommonMods();
        await this.getStoreConfig();
        this.tableMsgHandle = MessageHandleManager.Current.GetMessageHanle<TableMessageHandle>("TableMessageHandle");
        this.tableMsgHandle.OnMessage = async (table) => {
            console.log("this.tableMsgHandle.OnMessage", table);
            if (this.tableId != table.id) return;
            if (table.status == "" || table.status == "closed") {
                console.log("台桌结算消息");
                let confirmParams: ConfirmParams = {
                    content: "该台桌已经关台"
                }
                let result = await MessageBoxService.Current.Show(this.dialog, confirmParams);
                this.dialog.closeAll();
                // this.router.navigate(["table"]);
                this.navCtrl.popToRoot({ animate: false });
            }
        }

        /**
         * 订单结算消息处理
         */
        this.completePayMsghandle = MessageHandleManager.Current.GetMessageHanle<CompletePayMessagehandle>("CompletePayMessagehandle");
        this.completePayMsghandle.OnMessage = async (tableId) => {
            console.log("this.completePayMsghandle", tableId);
            if (this.tableId != (<any>tableId).id) {
                return;
            }
            let confirmParams: ConfirmParams = {
                content: "该台桌已经关台"
            }
            let result = await MessageBoxService.Current.Show(this.dialog, confirmParams);
            this.dialog.closeAll();
            // this.router.navigate(["table"]);
            this.navCtrl.popToRoot({ animate: false });
        }

        this.soldOutMsgHandle = MessageHandleManager.Current.GetMessageHanle<SoldOutMsgHandle>("SoldOutMsgHandle");
        this.soldOutMsgHandle.OnMessage = (data) => {
            if (data && data.length) {
                for (let soldOut of data) {
                    if (soldOut.isSoldOut) {
                        let obj: any = {};
                        obj.inventoryId = soldOut.id;
                        if (!this.soldOuts) {
                            this.soldOuts = [];
                        }
                        this.soldOuts.push(obj);
                    } else {
                        if (!this.soldOuts || !this.soldOuts.length) {
                            return;
                        }
                        for (let i = 0; i < this.soldOuts.length; i++) {
                            if (this.soldOuts[i].inventoryId == soldOut.id) {
                                this.soldOuts.splice(i, 1);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    ngOnDestroy() {
        if (this.sub) {
            this.sub.unsubscribe();
        }
    }

    async onCategoryClick(category) {
        this.loadingInvt = true;
        if (this.checkedCatetory && (<any>this.checkedCatetory).id == category.id) {
            this.loadingInvt = false;
            return;
        }
        this.listPage = 1;
        this.disabledScroll = false;
        if (this.invtList) {
            this.invtList.nativeElement.scrollIntoView({ block: "start", behavior: "smooth" });
        }
        this.checkedCatetory = category;
        this.categoryList.forEach(item => { delete item.checked; });
        category.checked = true;
        this.inventoryList = await this.invtSvr.GetInventory({
            categoryId: category.id,
            page: this.listPage,
            pageCount: this.listPageCount
        });
        this.loadingInvt = false;
        this.checkInventoryInCart(this.inventoryList);
    }

    private checkInventoryInCart(inventoryList) {
        inventoryList.forEach(element => {
            let flag = false;
            this.cartSvr.CartList.forEach(item => {
                if (element.id == item.inventoryId) {
                    if (flag) {
                        element.Qty += item.qty;
                    } else {
                        element.Qty = item.qty;
                        flag = true;
                    }
                }
            });
        });
    }

    private getCheckedCategory() {
        for (let item of this.categoryList) {
            if (item.checked) return item;
        }
    }
    setKeyText(key) {
        this.key += key.model;
        this.searchInventory(this.key);
    }
    /**
     * 根据输入值查找商品
     */
    async searchInventory(key) {
        if (this.searchInvtList) {
            this.searchInvtList.nativeElement.scrollIntoView({ block: "start", behavior: "smooth" });
        }
        this.cachePage = 1;
        this.cachePageCount = 10;
        this.disabledCacheScroll = false;
        key = key.trim();
        this.searchInventories = await this.invtSvr.GetInventory({
            code: key,
            page: this.cachePage,
            pageCount: this.cachePageCount
        });
    }

    /**
     * 查询更多的商品，搜索模式
     */
    async loadMoreInvtFromCache() {
        if (!CacheManager.Current.isCached("invtList")) {
            return;
        }
        if (this.queryCacheDataing || this.disabledCacheScroll) {
            return;
        }
        this.queryCacheDataing = true;
        let result = [];
        this.cachePage++;
        result = await this.invtSvr.GetInventory({
            code: this.key,
            page: this.cachePage,
            pageCount: this.cachePageCount,
        });
        if (!result || result.length < this.cachePageCount) {
            this.disabledCacheScroll = true;
        }
        this.searchInventories = this.searchInventories.concat(result);
        this.queryCacheDataing = false;
    }

    /**
     * 确认搜索
     */
    doEnter($event) {
        // this.searchInventory(this.key);
        if (Array.isArray(this.searchInventories) && this.searchInventories.length) {
            let isSoldOut = this.checkIsSoldOut(this.searchInventories[0].id);
            if (isSoldOut) {
                return;
            }
            this.InventoryListAddToCart(this.searchInventories[0], $event);
        }
    }

    /**
     * 退格键
     */
    backSpace() {
        if (this.key && this.key.length) {
            this.key = this.key.substring(0, this.key.length - 1)
        } else {
            this.key = "";
        }
        this.searchInventory(this.key);
    }

    /**
     * 清空输入
     */
    doReset() {
        this.key = "";
        this.searchInventory(this.key);
    }
    goBack() {
        // return this.router.navigate(["table/item", this.tableId, this.zoneId]);
        this.navCtrl.pop({ animate: false });
    }
    navGoBack() {
        let backBtn = document.getElementById("order-back-btn");
        if (backBtn) {
            backBtn.click();
        }
        this.dialog.closeAll();
    }
    selectInventory: Inventory;
    currentCartItem: Cart = <any>{ extended: {} };
    /**
     * 菜品列表界面 底部弹出偏好界面按钮
     * @param  {Inventory} inventory
     */
    async ShowModifier(cartItem) {
        let crt = await this.DoModifierSelect(cartItem);
        if (crt) {
            this.cartSvr.UpdateCart(crt);
        }
    }

    private async DoModifierSelect(cartItem, require?: boolean) {
        let crt = await OrderMoreService.Current.Open(this.dialog, cartItem, this.commonMods, require);
        // let crt = await OrderMoreService.Current.Open(cartItem.inventory, cartItem, this.commonMods, require);
        this.router.registGoBack(this.navGoBack.bind(this));
        if (!crt) {
            return false;
        }
        this.currentCartItem = crt;
        return crt;
    }

    private removeFromCart(cartItem) {
        cartItem.inventory.Qty = 0;
        this.cartSvr.RemoveCart(cartItem);

        let c = this.cartSvr.GetCartItemByInventoryId(cartItem.inventory.id);
        if (c) {
            cartItem.inventory.Qty = c.qty;
        }
        this.onCartRemove(cartItem.inventory);
    }

    onCartRemove(inventory: Inventory) {
        let item = this.inventoryList.find(x => x.id == inventory.id);
        if (item) {
            item.Qty = (<any>inventory).Qty;
        }

        this.currentCartItem = this.cartSvr.GetLastCartItem();
        if (this.currentCartItem) {
            this.selectInventory = this.inventoryList.find(x => x.id == this.currentCartItem.inventoryId);
        }
        else {
            this.selectInventory = null
        }
        let cartList = this.cartSvr.CartList;
        if (cartList && !cartList.length && this.endSideNav) {
            (<any>this.endSideNav).close();
        }
    }



    /**
     * 菜品列表中加入到购物车
     * @param  {Inventory} inventory 菜品对象
     */
    async InventoryListAddToCart(inventory: Inventory, $event?) {
        if (inventory.Qty >= this.maxInvtQty) {
            this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "最大输入数量为" + this.maxInvtQty);
            return;
        }
        if ($event) {
            $event.stopPropagation();
        }
        if (this.searchInventories) {
            this.searchInventories = [];
            this.key = "";
        }
        //判断是否有商品必选项，有直接弹出选项窗体
        let require = this.invtSvr.hasRequire(inventory, this.commonMods);
        let isCombo = this.isComboInvt(inventory);
        let cartTmp;
        if (require || isCombo) {
            let cartItem = this.cartSvr.CreateCartItem(inventory, null);
            let crt = await this.DoModifierSelect(cartItem, true);
            if (crt) {
                //加入到购物车
                cartTmp = crt;
                if (inventory.unit && inventory.unit.unitType == "weight") {
                    let result: any = await this.operateWeightInvt(inventory);
                    if (result) {
                        crt.qty = Number(result);
                        crt.amount = crt.amount * crt.qty;
                        inventory.Qty = Number(result);
                        this.cartSvr.AddCart(crt);
                    }
                } else {
                    if (inventory.Qty) {
                        inventory.Qty += 1;
                    } else {
                        inventory.Qty = 1;
                    }
                    this.cartSvr.AddCart(crt);
                }
            } else {
                return;
            }

        }
        else {
            let cartItem = this.cartSvr.GetNormalCartItemByInventoryId(inventory.id);
            if (inventory.unit && inventory.unit.unitType == "weight") {
                cartTmp = this.cartSvr.CreateCartItem(inventory, null);
                let result: any = await this.operateWeightInvt(inventory);
                if (result) {
                    cartTmp.qty = Number(result);
                    cartTmp.amount = cartTmp.amount * cartTmp.qty;
                    if (inventory.Qty) {
                        inventory.Qty += Number(result);
                    } else {
                        inventory.Qty = Number(result);
                    }
                    this.cartSvr.AddCart(cartTmp);
                }
            } else {
                if (cartItem) {
                    if (cartItem.modifiers && cartItem.modifiers.items.length > 0) {
                        //上一次的购物车项如果有偏好设定，这一次就新增购物车
                        cartTmp = this.cartSvr.CreateCartItem(inventory, null);
                        this.cartSvr.AddCart(cartTmp);
                    }
                    else {
                        cartTmp = cartItem;
                        cartItem.qty += 1;
                        cartItem.amount = (cartItem.qty * cartItem.price);
                        this.cartSvr.UpdateCart(cartItem);
                    }
                } else {
                    cartTmp = this.cartSvr.CreateCartItem(inventory, null);
                    this.cartSvr.AddCart(cartTmp);
                }

                if (inventory.Qty) {
                    inventory.Qty += 1;
                } else {
                    inventory.Qty = 1;
                }
            }
        }
        this.setcartItemCombo(cartTmp, isCombo);
        //更新订单详情页面购物车信息
        let cartItems = this.cartSvr.QueryCartList({ inventoryId: inventory.id });
        // OrderDetailService.Current.updateCartItems(cartItems);
        // this.orderDetailComponent.scrollEnd();
        this.selectInventory = inventory;
    }

    async operateWeightInvt(inventory) {
        let invtName = inventory.name;
        let title = `输入“${invtName}”的重量(${inventory.unit.name})`;
        let isDecimals = false;
        if (inventory.unit && inventory.unit.unitType == 'weight') {
            isDecimals = true;
        }
        let result = await NumberPanelService.current.open(this.dialog, title, null, null, isDecimals);
        return result;
    }

    /**
     * 设置套餐信息
     * @param  {Cart} cartItem  当前购物车项
     * @param  {boolean} isCombo  套餐是否默认选择（是否可以修改数量） true为可修改，可修改时会直接进入商品选项弹出框(orderMore)
     */
    private async setcartItemCombo(cartItem: Cart, isCombo: boolean) {
        try {
            if (!cartItem) {
                return;
            }
            if (!isCombo) {
                let comboObj = {
                    group: []
                }
                let invt = cartItem.inventory;
                if (invt.combo && invt.combo.group) {
                    for (let gro of invt.combo.group) {
                        let group = <any>{};
                        let totalSelectQty = 0;
                        let groupItems = [];
                        for (let item of gro.items) {
                            totalSelectQty += item.selectedQty;
                            let invt = await this.invtSvr.GetInventoryById(item.id);
                            let obj = this.invtSvr.buildCombo(invt, item);
                            groupItems.push(obj);
                        }
                        group.id = gro.id
                        group.name = gro.name;
                        group.items = groupItems;
                        comboObj.group.push(group);
                    }
                }
                cartItem.extended.combo = comboObj;
            }
        } catch (error) {
            console.log("Error:", error);
        }

    }

    private isComboInvt(inventory: Inventory) {
        let flag = false;
        if (inventory.combo && inventory.combo.group && inventory.combo.group.length) {
            for (let gro of inventory.combo.group) {
                if (gro.choiceQty) {
                    flag = true;
                }
            }
        }
        return flag;
    }

    /**
     * 菜品列表界面购物车减一
     * @param  {} inventory
     */
    InventoryListMinusFromCart(inventory: Inventory, $event) {
        $event.stopPropagation();
        console.log("从购物车数量-1");
        if (inventory.Qty && inventory.Qty > 1) {
            inventory.Qty -= 1;
        }
        else {
            inventory.Qty = 0;
        }

        // let cartItem = this.cartSvr.GetNormalCartItemByInventoryId(inventory.id);
        let cartItem = this.cartSvr.GetLastCartItemByInventoryId(inventory.id);
        let cartItemAmount = this.cartSvr.QueryCartList({ inventoryId: inventory.id });
        if (cartItem) {
            cartItem.qty -= 1;
            cartItem.amount = (cartItem.qty * cartItem.price);
            let amount = 0;
            amount = this.getInventoryAmountInCart(cartItemAmount);
            if (cartItem.qty > 0) {
                this.cartSvr.UpdateCart(cartItem);
                this.selectInventory = cartItem.inventory;
                (<any>this.selectInventory).Qty = amount;/*cartItem.qty*/
            }
            else {
                this.cartSvr.RemoveCart(cartItem);
                if (cartItemAmount.length) {
                    let cartItemNew = cartItemAmount[cartItemAmount.length - 1];
                    if (cartItemNew) {
                        this.selectInventory = cartItemNew.inventory;
                        (<any>this.selectInventory).Qty = this.getInventoryAmountInCart(cartItemAmount);
                    } else {
                        this.selectInventory = null;
                    }
                } else {
                    let lastCartItem = this.cartSvr.GetLastCartItem();
                    if (lastCartItem) {
                        this.selectInventory = lastCartItem.inventory;
                        (<any>this.selectInventory).Qty = lastCartItem.qty;
                    }
                    else {
                        this.selectInventory = null;
                    }
                }

            }
        }
    }
    /**
     * 计算购物车中的商品总数，当某项购物车中的商品数量为0时，移除该项
     * @param  {} cartItemList
     */
    private getInventoryAmountInCart(cartItemList) {
        let amount = 0;
        for (let i = 0; i < cartItemList.length; i++) {
            if (cartItemList[i].qty) {
                amount += cartItemList[i].qty;
            } else {
                cartItemList.splice(i, 1);
                i--;
            }
        }
        return amount;
    }

    async CartViewPlus(cartItem: Cart, num?: number) {
        if (cartItem.qty >= this.maxInvtQty) {
            this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "最大输入数量为" + this.maxInvtQty);
            return;
        }
        if (num) {
            cartItem.qty = num;
        } else {
            cartItem.qty += 1;
        }

        cartItem.amount = cartItem.qty * cartItem.price;
        if (cartItem.modifiers) {
            cartItem.amount += ((cartItem.modifiers.amount ? cartItem.modifiers.amount : 0) * cartItem.qty);
        }
        this.checkInventoryInCart(this.inventoryList);
    }
    async CartViewMinus(cartItem: Cart) {
        if (cartItem.qty > 1) {
            cartItem.qty -= 1;
            cartItem.amount = cartItem.qty * cartItem.price;
            if (cartItem.modifiers) {
                cartItem.amount += ((cartItem.modifiers.amount ? cartItem.modifiers.amount : 0) * cartItem.qty);
            }
        }
        this.checkInventoryInCart(this.inventoryList);
    }
    async CartViewDelete(cartItem: Cart, end) {
        let confirmParams: ConfirmParams = {
            title: "删除确认",
            content: "是否删除购物车项目【" + cartItem.inventoryName + "】？"
        }
        let msgResult = await MessageBoxService.Current.Show(this.dialog, confirmParams);
        if (msgResult == MessageResult.Ok) {
            this.removeItemFromCart(cartItem);
            let cartList = this.cartSvr.CartList;
            if (cartList && !cartList.length && end) {
                end.close();
            }
        }
    }

    plusFromCart($event, cartItem: Cart) {
        $event.stopPropagation();
        this.CartViewPlus(cartItem);
    }

    minusFromCart($event, cartItem: Cart) {
        $event.stopPropagation();
        this.CartViewMinus(cartItem);
    }

    delFromCart($event, cartItem: Cart, end) {
        $event.stopPropagation();
        this.CartViewDelete(cartItem, end);
    }
    /**
     * 移除购物车中指定的项
     * @param  {} cartItem
     */
    removeItemFromCart(cartItem) {
        this.cartSvr.RemoveCart(cartItem);
        let inventoryId = cartItem.inventoryId;
        let c = this.cartSvr.GetCartItemByInventoryId(inventoryId);
        let inventory = this.inventoryList.find(x => x.id == inventoryId);
        if (inventory) {
            if (c) {
                (<any>inventory).Qty = c.qty;
            }
            else (<any>inventory).Qty = 0;
        }

        let lastCartItem = this.cartSvr.GetLastCartItem();
        if (lastCartItem) {
            this.selectInventory = lastCartItem.inventory;
            (<any>this.selectInventory).Qty = lastCartItem.qty;
        }
        else this.selectInventory = null;
    }

    async CartViewShowModifier(cartItem: Cart) {
        let allInvts = await this.invtSvr.GetInventory();
        let inventory = allInvts.find(x => x.id == cartItem.inventoryId);
        if (!inventory) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, "未找到当前商品");
            return;
        }
        let crt = await OrderMoreService.Current.Open(this.dialog, cartItem, this.commonMods);
        this.router.registGoBack(this.navGoBack.bind(this));
    }

    goToDoOrder(end) {
        end.open();
        this.currentOrder = new Order();
        this.currentOrder.id = guid();
        this.currentOrder.cart.items = this.cartSvr.CartList;
    }

    async onConfirmOrder() {
        let cartList = this.cartSvr.CartList;
        if (!cartList || !cartList.length) {
            this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "没有订单数据");
            return;
        }
        let data = await OrderConfirmService.Current.Open(this.dialog, this.tableId, this.commonRemarks);
        this.router.registGoBack(this.navGoBack.bind(this));
        if (!data) {
            return;
        }
        let orderTables = (<any>data).selectTables;
        if (data && orderTables && Array.isArray(orderTables) && orderTables.length) {
            if (orderTables.length == 1) {
                await this.Ordering(this.currentOrder, (<any>data).remark);
            } else if (orderTables.length > 1) {
                await this.mergeOrdering(this.currentOrder, orderTables, (<any>data).remark);
            }
        }
    }

    async getStoreConfig() {
        this.commonRemarks = await this.storeSvr.getStoreConfigs("order.process.note");
    }

    /**
     * 下单按钮的处理逻辑
     */
    @loadingMask()
    async Ordering(order: Order, orderRemark?: string) {
        try {
            if (orderRemark) {
                order.description = orderRemark;
            }
            let r = await this.tableSvr.Ordering(order, this.currentTable);
            this.printOrder([r]);
            this.msgSvr.Growl(GrowlMessageType.Info, this.snackBar, "下单成功!");
            let that = this;
            //通知到Pos端打印
            this.orderPrintFNCMsg(that, r);
            //通知到其他终端
            FNCManager.Current.InnerMessageNotify(InnerMessageType.OrderMsg, r);
            console.log("orderPrint消息已经发送：", r);
            this.currentOrder = new Order();
            this.goBack();
        }
        catch (err) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, err ? err : "下单失败");
            this.navCtrl.pop({ animate: false });
        }
    }
    /**
     * 打印订单
     * @param preOrder 
     */
    async printOrder(preOrders) {
        let store: any = await this.storeSvr.getStoreInfo();
        if (store && store.setting) {
            let isEnablePrint = store.setting.receipt.preOrder.whetherPrint;
            if (!isEnablePrint) {
                return false;
            }
        }
        let printers = this.printerManager.getAllDevices();
        if (!printers || !printers.length) {
            console.log("未添加打印机");
            return;
        }
        let printTasks: any = await this.createPrintTask(printers, preOrders);
        await this.invokePrintTasks(printTasks);
    }
    /**
     * 创建打印任务
     */
    async createPrintTask(printers, preOrders) {
        let tasks = [];
        if (Array.isArray(preOrders) && preOrders.length) {
            for (let preOrder of preOrders) {
                let printParams: PrintParams = {
                    token: this.cartSvr.Token,
                    store: this.cartSvr.CurrentStore,
                    isTestPrint: false,
                    printers: printers,
                    preOrder: preOrder
                }
                let result: any = await PrintComponentService.current.show(printParams);
                if (Array.isArray(result)) {
                    result.forEach(r => {
                        r.tableName = preOrder.extended.table.name;
                        tasks.push(r);
                    });
                } else {
                    result.tableName = preOrder.extended.table.name;
                    tasks.push(result);
                }
            }
        }
        return tasks;
    }

    /**
     * 执行打印任务
     * @param printTasks 
     */
    async invokePrintTasks(printTasks) {
        let allTasks = await Promise.all(
            printTasks.map(async (task) => {
                try {
                    let result = await this.printerManager.printHtml(task);
                    let msg = this.printerManager.errMsg(result.data);
                    let tableName = task.tableName;
                    return { task, msg, tableName };
                } catch (error) {
                    console.log(error);
                }
            })
        )
        let failedTasks = allTasks.filter(task => (<any>task).msg);
        if (Array.isArray(failedTasks) && failedTasks.length) {
            let tableNames = [];
            let names = "";
            failedTasks.forEach((task) => {
                let name = "【" + (<any>task).tableName + "】";
                tableNames.push(name);
            });
            names = tableNames.join("、");
            let confirmParams: ConfirmParams = {
                title: "打印失败",
                content: "台桌" + names + "记账单打印失败！",
                confirmText: "重新打印",
                cancelText: "忽略",
            }
            let info = await MessageBoxService.Current.Show(this.dialog, confirmParams);
            if (info == MessageResult.Ok) {
                let tasks = [];
                failedTasks.forEach((taskItem) => {
                    (<any>taskItem).task.tableName = (<any>taskItem).tableName
                    tasks.push((<any>taskItem).task);
                })
                this.invokePrintTasks(tasks);
            }
        }
    }

    /**
     * 通知POS打印订单
     * @param that 
     * @param r 
     */
    orderPrintFNCMsg(that, r) {
        FNCManager.Current.FNC.Notify({ type: "orderPrint", content: r }).catch(async (error) => {
            let params: ConfirmParams = {
                title: "打印失败",
                content: "是否重新打印台桌" + that.currentTable.name + "下的订单,订单编号：" + r.id
            }
            let result = await MessageBoxService.Current.Show(that.dialog, params);
            if (result == MessageResult.Ok) {
                that.orderPrintFNCMsg(that, r);
            }
        });
    }

    onInventoryClick(invt) {
        //TODO 暂时隐藏该页面
        // let boo = this.checkIsSoldOut(invt.id);
        // if (boo) {
        //     return;
        // }
        // this.currentInvt = invt;
        // let inventories = this.cartSvr.QueryCartList({ inventoryId: invt.id });
        // OrderDetailService.Current.open(this.currentInvt, inventories);
    }

    /**
     * 下单到并台台桌
     */
    @loadingMask()
    async mergeOrdering(order: Order, tables, remark?: string) {
        try {
            if (remark) {
                order.description = remark;
            }
            let result = await this.tableSvr.mergeOrdering(order, tables);
            let that = this;
            if (Array.isArray(result) && result.length) {
                let preOrders = [];
                result.forEach(r => {
                    //通知到Pos端打印
                    this.orderPrintFNCMsg(that, r.body);
                    preOrders.push(r.body);
                    //通知到其他终端
                    FNCManager.Current.InnerMessageNotify(InnerMessageType.OrderMsg, r.body);
                });
                this.printOrder(preOrders);
            }
            this.msgSvr.Growl(GrowlMessageType.Info, this.snackBar, "下单成功!");
            this.goBack();
        } catch (error) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, error ? error : "下单失败");
        }
    }

    /**
     * 展开或者隐藏键盘
     */
    toggleKeyboard() {
        this.showKeyboard = !this.showKeyboard;
        if (!this.showKeyboard) {
            this.rd.invokeElementMethod(this.searchInput.nativeElement, "focus");
        }
    }

    /**
     * 切换搜索模式
     */
    toggleSearchModel() {
        this.searchModel = !this.searchModel;
    }
    /**
     * 检测是否售罄
     * @param invtId  商品的id 
     */
    checkIsSoldOut(invtId) {
        if (this.soldOuts && this.soldOuts.length) {
            let invt = this.soldOuts.find((sold) => {
                return sold.inventoryId == invtId;
            });
            if (invt) {
                return true;
            }
        }
        return false;
    }
    /**
     * 滚动时分页查询数据
     */
    async onScroll() {
        if (this.disabledScroll || this.queryDataing) {
            return;
        }
        this.queryDataing = true;
        this.listPage++;
        let list = await this.invtSvr.GetInventory({
            categoryId: (<any>this.checkedCatetory).id,
            page: this.listPage,
            pageCount: this.listPageCount
        });
        this.queryDataing = false;
        if (!list || !list.length) {
            this.disabledScroll = true;
        } else {
            this.inventoryList = this.inventoryList.concat(list);
            this.disabledScroll = false;
        }
    }

    /**
     * 筛选出售罄的商品
     */
    private handleSoldout(soldouts) {
        let result = [];
        // if (Array.isArray(soldouts) && soldouts.length) {
        //     result = soldouts.filter((sold) => {
        //         return !sold.disabled;
        //     })
        // }
        for (let sold of soldouts) {
            let obj: any = {};
            if (sold.isSoldOut == true) {
                obj.inventoryId = sold.id;
                obj.name = sold.name
                result.push(obj);
            }
        }
        return result;
    }

    /**
     * 获得当前分类下点了几个商品
     */
    getInvtCate(category) {
        let list = this.cartSvr.CartList;
        if (!list || !list.length) {
            return false;
        }
        let result = list.filter(cart => {
            let r = cart.inventory.categories.find(cate => {
                return cate.id == category.id;
            });
            if (r) {
                return true;
            }
            return false;
        });
        if (result) {
            return result.length;
        }
        return false;
    }

    /**
     * 展开或收起侧边栏
     */
    openWaitingPickUp() {
        (<any>this.pickup).toggle();
    }
    /**
     * 等叫
     */
    async waitingPickUp() {
        (<any>this.pickup).close();
        let result: any = await OrderPickUpService.current.open(this.dialog, "waiting", this.cartSvr.CartList);
        if (result) {
            lodash(this.cartSvr.CartList).forEach(item => {
                delete item.extended.pickup;
            })
            lodash(result).forEach(waitItem => {
                let target: any = this.cartSvr.CartList.find(cart => {
                    return waitItem.id == cart.id;
                });
                if (target) {
                    target.extended.pickup = "waiting";
                }
            });
        }
    }
    closeEnd(end) {
        if (end) {
            end.close();
        }
    }
    /**
     * 打开数字选择面板
     */
    async openPanel(inventory, cartItem?, $event?) {
        if ($event) {
            $event.stopPropagation();
        }
        let cartItemQuery = null;
        if (cartItem) {
            cartItemQuery = cartItem;
        } else {
            cartItemQuery = this.cartSvr.GetLastCartItemByInventoryId(inventory.id);
        }
        let weightText = (inventory.unit && inventory.unit.unitType == 'weight') ? '重量' : '数量';
        let invtName = `输入“${inventory.name}”的${weightText}`;
        let isDecimal = false;
        if (inventory.unit && inventory.unit.unitType == 'weight') {
            isDecimal = true;
        }
        let result = await NumberPanelService.current.open(this.dialog, invtName, null, cartItemQuery.qty, isDecimal);
        if (result != undefined) {
            if (result == 0) {
                this.removeItemFromCart(cartItemQuery);
            } else if (result && Number(result)) {
                this.CartViewPlus(cartItemQuery, Number(result));
            }
        }
    }

    getInvtInCartNum(invt) {
        let cartList = this.cartSvr.CartList;
        if (cartList && cartList.length) {
            let invts = cartList.filter(cart => {
                return invt.id == cart.inventoryId;
            });
            if (invts && invts.length) {
                return "x" + invts.length;
            }
        }
        return "";
    }
}
